//
//===========================================================================
//
// Ynote Classic Syntax Highlighter
//
// Copyright (C) 2013 Samarjeet Singh
// 
//
// C#, VB, PHP, JS, HTML, SQL Code from FastColoredTextBoxNS.SyntaxHighlighter
//
//===========================================================================
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FastColoredTextBoxNS;
using System.Text.RegularExpressions;
using System.Drawing;

namespace SS.Ynote.Classic
{
    /// <summary>
    /// Predifined Syntax Highlighter
    /// </summary>
    public class SyntaxHighlighter
    {
        #region Properties
        /// <summary>
        /// Regex Compiled Options YnoteSettingsBased on Platform x86 | x64
        /// </summary>
        static RegexOptions RegexCompiledOption
        {
            get
            {
                if (PlatformType.GetOperationSystemPlatform() == Platform.X86)
                    return RegexOptions.Compiled;
                else
                    return RegexOptions.None;
            }
        }
        /// <summary>
        /// String style
        /// </summary>
        public Style StringStyle { get; set; }
        /// <summary>
        /// Comment style
        /// </summary>
        public Style CommentStyle { get; set; }
        /// <summary>
        /// Number style
        /// </summary>
        public Style NumberStyle { get; set; }
        /// <summary>
        /// C# attribute style
        /// </summary>
        public Style AttributeStyle { get; set; }
        /// <summary>
        /// Class name style
        /// </summary>
        public Style ClassNameStyle { get; set; }
        /// <summary>
        /// Char Style
        /// </summary>
        public Style CharStyle { get; set; }
        /// <summary>
        /// Keyword style
        /// </summary>
        public Style KeywordStyle { get; set; }
        /// <summary>
        /// Style of tags in comments of C#
        /// </summary>
        public Style CommentTagStyle { get; set; }

        /// <summary>
        /// HTML attribute value style
        /// </summary>
        public Style AttributeValueStyle { get; set; }
        /// <summary>
        /// HTML tag brackets style
        /// </summary>
        public Style TagBracketStyle { get; set; }
        /// <summary>
        /// HTML tag name style
        /// </summary>
        public Style TagNameStyle { get; set; }
        /// <summary>
        /// HTML Entity style
        /// </summary>
        public Style HtmlEntityStyle { get; set; }

        /// <summary>
        /// Variable style
        /// </summary>
        public Style VariableStyle { get; set; }

        /// <summary>
        /// Specific PHP keyword style
        /// </summary>
        public Style KeywordStyle2 { get; set; }
        /// <summary>
        /// Specific PHP keyword style
        /// </summary>
        public Style KeywordStyle3 { get; set; }

        /// <summary>
        /// SQL Statements style
        /// </summary>
        public Style StatementsStyle { get; set; }
        /// <summary>
        /// SQL Functions style
        /// </summary>
        public Style FunctionsStyle { get; set; }
        /// <summary>
        /// SQL Types style
        /// </summary>
        public Style TypesStyle { get; set; }
        /// <summary>
        /// CSS Selector Style
        /// </summary>
        public Style CSSSelectorStyle { get; set; }
        /// <summary>
        /// CSS Property Style
        /// </summary>
        public Style CSSPropertyStyle { get; set; }
        /// <summary>
        /// Python/Ruby Class Name Style
        /// </summary>
        public Style ClassNameStyle2 { get; set; }

        #endregion

        #region Constructor

        /// <summary>
        /// Default Constructor
        /// </summary>
        public SyntaxHighlighter()
        {
            // Init();
        }
        #endregion

        #region Public Methods

        /// <summary>
        /// Highlight Syntax
        /// </summary>
        /// <param name="Language"></param>
        public void HighlightSyntax(Language Language, Range range)
        {
            switch (Language)
            {
                case FastColoredTextBoxNS.Language.Actionscript: JavaAsHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Assemblyx86: ASMSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Batch: BatchSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.C: CPPSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.CPP: CPPSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.CSS: CSSHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.CSharp: CSharpSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.D: DSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Java: JavaAsHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Lua: LuaSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.ASP: HTMLSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Python: PythonSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.QBasic: QBHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Perl: PerlSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Ruby: RubySyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Xml: XmlSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Xml;
                    break;
                case FastColoredTextBoxNS.Language.INI: INISyntaxHighlight(range);
                    break;
                case Language.JSON: JSONSyntaxHighlight(range);
                    break; 
                case FastColoredTextBoxNS.Language.VB: VBSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.HTML: HTMLSyntaxHighlight(range); 
                    break;
                case FastColoredTextBoxNS.Language.Javascript: JScriptSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.SQL: SQLSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.PHP: PHPSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.OpenCL: CLHighlight(range, BuildExplorerItems(range));
                    break;
                case FastColoredTextBoxNS.Language.Lisp: LispSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.FSharp: FSharpSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Pascal: PascalSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Scala: ScalaSyntaxHighlight(range);
                    break;
            }
        }
        /// <summary>
        /// Set Syntax
        /// </summary>
        /// <param name="Language"></param>
        /// <param name="range"></param>
        public void SetSyntax(Language Language, Range range)
        {
            switch (Language)
            {
                case FastColoredTextBoxNS.Language.Actionscript: JavaAsHighlight(range);
                    range.tb.Language = Language.Actionscript;
                    break;
                case FastColoredTextBoxNS.Language.Assemblyx86: ASMSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Assemblyx86;
                    break;
                case FastColoredTextBoxNS.Language.Text: range.tb.Language = FastColoredTextBoxNS.Language.Text;
                    range.tb.ClearStylesBuffer();
                    break;
                case FastColoredTextBoxNS.Language.CSharp: range.tb.Language = FastColoredTextBoxNS.Language.CSharp;
                    CSharpSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Batch: BatchSyntaxHighlight(range);
                    range.tb.Language = Language.Batch;
                    break;
                case FastColoredTextBoxNS.Language.C: CPPSyntaxHighlight(range);
                    range.tb.Language = Language.C;
                    break;
                case FastColoredTextBoxNS.Language.CPP: CPPSyntaxHighlight(range);
                    range.tb.Language = Language.CPP;
                    break;
                case FastColoredTextBoxNS.Language.QBasic: QBHighlight(range);
                    range.tb.Language = Language.QBasic;
                    break;
                case FastColoredTextBoxNS.Language.D: DSyntaxHighlight(range);
                    range.tb.Language = Language.D;
                    break;
                case FastColoredTextBoxNS.Language.CSS: CSSHighlight(range);
                    range.tb.Language = Language.CSS;
                    break;
                case FastColoredTextBoxNS.Language.HTML: range.tb.Language = FastColoredTextBoxNS.Language.HTML;
                    HTMLSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.FSharp: range.tb.Language = FastColoredTextBoxNS.Language.FSharp;
                    FSharpSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Java: JavaAsHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Java;
                    break;
                case FastColoredTextBoxNS.Language.Javascript: range.tb.Language = FastColoredTextBoxNS.Language.Javascript;
                    JScriptSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.OpenCL: range.tb.Language = FastColoredTextBoxNS.Language.OpenCL;
                    CLHighlight(range, BuildExplorerItems(range));
                    break;
                case FastColoredTextBoxNS.Language.Lua: LuaSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Lua;
                    break;
                case FastColoredTextBoxNS.Language.ASP: HTMLSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.HTML;
                    break;
                case FastColoredTextBoxNS.Language.PHP: range.tb.Language = FastColoredTextBoxNS.Language.PHP;
                    PHPSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Python: PythonSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Python;
                    break;
                case FastColoredTextBoxNS.Language.Perl: PerlSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Perl;
                    break;
                case FastColoredTextBoxNS.Language.Pascal: PascalSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Pascal;
                    break;
                case FastColoredTextBoxNS.Language.Ruby: RubySyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Ruby;
                    break;
                case FastColoredTextBoxNS.Language.Scala: ScalaSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Scala;
                    break;
                case FastColoredTextBoxNS.Language.SQL: range.tb.Language = FastColoredTextBoxNS.Language.SQL;
                    SQLSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.VB: range.tb.Language = FastColoredTextBoxNS.Language.VB;
                    VBSyntaxHighlight(range);
                    break;
                case FastColoredTextBoxNS.Language.Xml: XmlSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Xml;
                    break;
                case FastColoredTextBoxNS.Language.INI: INISyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.INI;
                    break;
                case Language.JSON: JSONSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.JSON;
                    break; ;
                case Language.Lisp: LispSyntaxHighlight(range);
                    range.tb.Language = FastColoredTextBoxNS.Language.Lisp;
                    break;
            }
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Regexes
        /// </summary>
            Regex CSSStringRegex;
            Regex CSSCommentRegex2;
            Regex CSSCommentRegex3;
            Regex CSSNumberRegex;
            Regex CSSPropertyRegex;
            Regex CSSSelectorRegex;
        /// <summary>
        /// Init CSS Regex
        /// </summary>
        void InitCSSRegex()
        {
            CSSStringRegex = new Regex(@"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            CSSCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline);
            CSSCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft);
            CSSNumberRegex = new Regex(@"\d+[\.]?\d*(pt|px|\%|em)?");
            CSSPropertyRegex = new Regex(@"(?<![\-\w])(animation|animation|animation-name|animation-duration|animation-timing-function|animation-delay|animation-iteration-count|animation-direction|animation-play-state|appearance|backface-visibility|background|background|background-attachment|background-color|background-image|background-position|background-repeat|background-clip|background-origin|background-size|border|border|border-bottom|border-bottom-color|border-bottom-style|border-bottom-width|border-collapse|border-color|border-left|border-left-color|border-left-style|border-left-width|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-style|border-top-width|border-width|border-bottom-left-radius|border-bottom-right-radius|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-radius|border-top-left-radius|border-top-right-radius|bottom|box|box-align|box-direction|box-flex|box-flex-group|box-lines|box-ordinal-group|box-orient|box-pack|box-sizing|box-shadow|caption-side|clear|clip|color|column|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|float|font|font|font-family|font-size|font-style|font-variant|font-weight|@font-face|font-size-adjust|font-stretch|grid-columns|grid-rows|hanging-punctuation|height|icon|@keyframes|left|letter-spacing|line-height|list-style|list-style|list-style-image|list-style-position|list-style-type|margin|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|outline|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding|padding-bottom|padding-left|padding-right|padding-top|page-break|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|punctuation-trim|quotes|resize|right|rotation|rotation-point|table-layout|target|target|target-name|target-new|target-position|text|text-align|text-decoration|text-indent|text-justify|text-outline|text-overflow|text-shadow|text-transform|text-wrap|top|transform|transform|transform-origin|transform-style|transition|transition|transition-property|transition-duration|transition-timing-function|transition-delay|vertical-align|visibility|width|white-space|word-spacing|word-break|word-wrap|z-index)(?![\-\w])", RegexOptions.IgnoreCase);
            CSSSelectorRegex = new Regex(@"\b(a|abbr|acronym|address|applet|area|article|aside|audio|b|YnoteSettingsBase|YnoteSettingsBasefont|bdi|bdo|big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr)\b|[#@\.][\w\-]+\b", RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// Highlight CSS Syntax
        /// </summary>
        /// <param name="r"></param>
        void CSSHighlight(Range r)
        {
            r.tb.CommentPrefix = "/*^*/";
            r.ClearStyle(CommentTagStyle, StringStyle, CSSPropertyStyle, NumberStyle);
           
            r.tb.RightBracket = '}';
            r.tb.LeftBracket2 = '(';
            r.tb.RightBracket2 = ')';
            r.tb.LeftBracket = '{';
            if (CSSStringRegex == null)
                InitCSSRegex();
            r.SetStyle(CommentTagStyle, CSSCommentRegex2);
            r.SetStyle(CommentTagStyle, CSSCommentRegex3);
            r.SetStyle(StringStyle, CSSStringRegex);
            r.SetStyle(CSSPropertyStyle, CSSPropertyRegex);
            r.SetStyle(CSSSelectorStyle, CSSSelectorRegex);
            r.SetStyle(NumberStyle, CSSNumberRegex);
            r.SetFoldingMarkers("{", "}");
        }
        void BatchSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "rem";
            r.tb.LeftBracket = '(';
            r.tb.RightBracket = ')';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, StringStyle, KeywordStyle ,KeywordStyle2, KeywordStyle3, CharStyle);
            r.SetStyle(CommentStyle,@"rem .*$", RegexOptions.Multiline|RegexOptions.IgnoreCase);
            r.SetStyle(StringStyle, @"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            r.SetStyle(KeywordStyle, @"\b(title|set|call|copy|exists|cut|cd|@|nul|choice|do|shift|sgn|errorlevel|con|prn|lpt1|echo|off|for|in|do|goto|if|then|else|not|end)\b");
            r.SetStyle(KeywordStyle2, @":.*$", RegexOptions.Multiline);
            r.SetStyle(KeywordStyle3, @"%.*?[^\\]%", RegexOptions.Multiline);
            r.SetStyle(CharStyle, @"\;|-|>|<|=|\+|\,|\$|\^|\[|\]|\$|:|\!");
        }
        void ActionscriptSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "//";
            r.ClearStyle(CommentStyle, StringStyle, KeywordStyle, NumberStyle);
            r.SetStyle(CommentStyle, "//.*$", RegexOptions.Multiline);
            r.SetStyle(CommentStyle, new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption));
            r.SetStyle(CommentStyle, new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption));
            r.SetStyle(StringStyle, @"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            r.SetStyle(KeywordStyle, @"\b()\b");
            throw new NotImplementedException();
        }
        Regex JavaStringRegex,JavaFunctionRegex,JavaKeywordRegex2, JavaCommentRegex1, JavaCommentRegex2, JavaCommentRegex3, JavaNumberRegex, JavaAttributeRegex, JavaClassNameRegex, JavaKeywordRegex;

        void InitJavaAsRegex()
        {
            JavaStringRegex = new Regex(@"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            JavaCommentRegex1 = new Regex(@"//.*$", RegexOptions.Multiline);
            JavaCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline);
            JavaCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft);
            JavaNumberRegex = new Regex(@"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b");
            JavaAttributeRegex = new Regex(@"^\s*(?<range>\[.+?\])\s*$", RegexOptions.Multiline);
            JavaClassNameRegex = new Regex(@"\b(class|struct|enum|interface)\s+(?<range>\w+?)\b");
            JavaKeywordRegex = new Regex(@"\b(abstract|as|import|package|extends|implements|boolean|final|assert|instanceof|native|strictfp|super|synchronized|throws|transient|YnoteSettingsBase|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b|#region\b|#endregion\b");
            JavaKeywordRegex2 = new Regex(@"\b(true|false)\b");
            JavaFunctionRegex = new Regex(@"\b(void|extends)\s+(?<range>\w+?)\b");
        }
        /// <summary>
        /// Java/Actionscript Highlight
        /// </summary>
        /// <param name="r"></param>
        void JavaAsHighlight(Range range)
        {
            range.tb.CommentPrefix = "//";
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '{';
            range.tb.RightBracket2 = '}';
            if (JavaStringRegex == null)
                InitJavaAsRegex();
            range.ClearStyle(CommentStyle, StringStyle, NumberStyle, ClassNameStyle, KeywordStyle, CharStyle);
            range.SetStyle(CommentStyle, JavaCommentRegex1);
            range.SetStyle(CommentStyle, JavaCommentRegex2);
            range.SetStyle(CommentStyle, JavaCommentRegex3);
            //string
            range.SetStyle(StringStyle, JavaStringRegex);
            //number highlighting
            range.SetStyle(NumberStyle, JavaNumberRegex);
            //attribute highlighting
            range.SetStyle(CommentStyle, JavaAttributeRegex);
            //class name highlighting
            range.SetStyle(ClassNameStyle, JavaClassNameRegex);
            range.SetStyle(ClassNameStyle2, JavaFunctionRegex);
            //keyword highlighting
            range.SetStyle(KeywordStyle, JavaKeywordRegex);
            range.SetStyle(KeywordStyle2, JavaKeywordRegex2);
            //Char Highlighting
            range.SetStyle(CharStyle, @"\;|-|>|<|=|\+|\,|\$|\^|\[|\]");
            range.ClearFoldingMarkers();
            range.SetFoldingMarkers("{", "}");
        }
        /// <summary>
        /// QBasic Syntax Highlight
        /// </summary>
        /// <param name="r"></param>
        private void QBHighlight(Range r)
        {
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, KeywordStyle);
            r.SetStyle(CommentStyle, "\'.*$", RegexOptions.Multiline);
            r.SetStyle(KeywordStyle, @"\b(ABS|AND|AS|ASC|ATN|YnoteSettingsBase|BEEP|BLOAD|BSAVE|CDBL|CHR\$|CINT|CIRCLE|CLEAR|CLNG|CLS|COLOR|COM|COMMAND$|CONST|COS|CSNG|CSRLIN|CSRUN|CVD|CVDMBF|CVI|CVL|CVS|CVSMBF|DATA|DATE$|DEF|DEFDBL|DEFINT|DEFLNG|DEFSNG|DEFSTR|DIM|DOUBLE|DRAW|ENVIRON|ENVIRON$|EQV|ERASE|ERDEV|ERDEV$|ERL|ERR|ERROR|EXP|FIX|FN|FRE|HEX$|IMP|INSTR|INT|INTEGER|KEY|LBOUND|LCASE$|LEFT$|LEN|LET|LINE|LIST|LOCATE|LOG|LONG|LPOS|LTRIM$|MID$|MKD$|MKDMBF$|MKI$|MKL$|MKS$|MOD|NOT|OCT$|OFF|ON|OPEN|OPTION|OR|OUT|OUTPUT|PAINT|PALETTE|PCOPY|PEEK|PEN|PLAY|PMAP|POINT|POKE|POS|PRESET|PSET|RANDOMIZE|READ|REDIM|RESTORE|RIGHT$|RND|RTRIM$|SADD|SCREEN|SEEK|SEG|SETMEM|SGN|SIGNAL|SIN|SINGLE|SLEEP|SOUND|SPACE$|SPC|SQR|STATIC|STICK|STOP|STR$|STRIG|STRING|STRING$|SWAP|TAB|TAN|TIME$|TIMER|TROFF|TRON|TYPE|UBOUND|UCASE$|UEVENT|VAL|VARPTR|VARPTR$|VARSEG|VIEW|WIDTH|WINDOW|XOR)\b", RegexOptions.IgnoreCase);
            r.SetStyle(KeywordStyle2, @"\b(ABSOLUTE|ALIAS|BYVAL|CALL|CALLS|CASE|CDECL|CHAIN|COMMON|DO|DECLARE|ELSE|ELSEIF|END|ENDIF|EXIT|FOR|FUNCTION|GOSUB|GOTO|IF|INT86OLD|INT86XOLD|INTERUPT|INTERUPTX|IS|LOCAL|LOOP|MERGE|NEXT|RESUME|RETURN|RUN|SELECT|SHARED|SHELL|STEP|SUB|SYSTEM|THEN|TO|UNTIL|WEND|WHILE|ACCESS|ANY|APPEND|BINARY|CHDIR|CLOSE|EOF|FIELD|FILEATTR|FILES|FREEFILE|GET|INKEY$|INP|INPUT|IOCTL|IOCTL$|KILL|LINE|LOC|LOCK|LOF|LPRINT|LSET|MKDIR|NAME|OPEN|OUT|OUTPUT|PRINT|PUT|RANDOM|RESET|RMDIR|RSET|SEEK|UNLOCK|USING|WAIT|WIDTH|WRITE)\b");
            r.SetStyle(VariableStyle, @"\$[a-zA-Z_\d]*\b", RegexCompiledOption);
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b");
        }
        Regex CPPCommentRegex1;
        Regex CPPCommentRegex2;
        Regex CPPCommentRegex3;
        Regex CPPNumberRegex;
        Regex CPPStringRegex;
        Regex CPPKeywordRegex;
        Regex CPPAttributeRegex;
        Regex CPPClassNameRegex;
        Regex CPPKeywordRegex2;
        Regex CPPFunctionsRegex;
        /// <summary>
        /// Init C++ Regex
        /// </summary>
        void InitCPPRegex()
        {
            CPPStringRegex = new Regex(@"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            CPPCommentRegex1 = new Regex(@"//.*$", RegexOptions.Multiline);
            CPPCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline);
            CPPCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft);
            CPPNumberRegex = new Regex(@"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b");
            CPPAttributeRegex = new Regex(@"^\s*(?<range>\[.+?\])\s*$", RegexOptions.Multiline );
            CPPKeywordRegex = new Regex(@"\b(abstract|class|interface|enum|event|delegate|break|base|case|break|default|typedef|as|catch|char|checked|const|continue|decimal|default|do|double|else|explicit|extern|finally|fixed|float|for|foreach|goto|if|implicit|in|int|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|struct|switch|this|throw|try|typeof|ulong|unchecked|unsafe|using|virtual|volatile|while|add|alias|ascending|descending|dynamic|from|get|global|group|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b");
            CPPClassNameRegex = new Regex(@"\b(class|struct|enum|interface)\s+(?<range>\w+?)\b");
            CPPKeywordRegex2 = new Regex(@"\b(void|byte|bool|string|int|ulong|ushort|uint|true|false)\b");
            CPPFunctionsRegex = new Regex(@"\b(void|int|bool|string|uint|ushort|ulong|byte)\s+(?<range>\w+?)\b");
        }
        /// <summary>
        /// C++ Syntax Highlight
        /// </summary>
        /// <param name="r"></param>
        void CPPSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "//";
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '{';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = '}';
            r.ClearStyle(CommentStyle, KeywordStyle, NumberStyle, CharStyle, ClassNameStyle, KeywordStyle3);
            if (CPPCommentRegex1 == null)
                InitCPPRegex();
            r.SetStyle(CommentStyle, CPPCommentRegex1);
            r.SetStyle(CommentStyle, CPPCommentRegex2);
            r.SetStyle(CommentStyle, CPPCommentRegex3);
            r.SetStyle(StringStyle, CPPStringRegex);
            r.SetStyle(KeywordStyle3, "#.*$", RegexOptions.Multiline);
            r.SetStyle(ClassNameStyle, CPPClassNameRegex);
            r.SetStyle(ClassNameStyle2, CPPFunctionsRegex);
            r.SetStyle(KeywordStyle, CPPKeywordRegex);
            r.SetStyle(KeywordStyle2, CPPKeywordRegex2);
            r.SetStyle(NumberStyle, CPPNumberRegex);
            r.SetStyle(CharStyle, @"\;|-|>|<|=|\+|\,|\$|\^|\[|\]|\$|\!|\?");
            r.ClearFoldingMarkers();
            r.SetFoldingMarkers("{", "}", RegexOptions.IgnoreCase);
            r.SetFoldingMarkers(@"#if", @"#end");
        }
        Regex HTMLTagRegex, HTMLTagNameRegex, HTMLEndTagRegex, HTMLAttrRegex, HTMLAttrValRegex, HTMLCommentRegex1, HTMLCommentRegex2, HTMLEntityRegex, HTMLTagContentRegex;

        void InitHTMLRegex()
        {
            HTMLCommentRegex1 = new Regex(@"(<!--.*?-->)|(<!--.*)", RegexOptions.Singleline);
            HTMLCommentRegex2 = new Regex(@"(<!--.*?-->)|(.*-->)", RegexOptions.Singleline | RegexOptions.RightToLeft);
            HTMLTagRegex = new Regex(@"<|/>|</|>|\?");
            HTMLTagNameRegex = new Regex(@"<(?<range>[!\w:]+)");
            HTMLEndTagRegex = new Regex(@"</(?<range>[\w:]+)>");
            HTMLTagContentRegex = new Regex(@"<[^>]+>");
            HTMLAttrRegex = new Regex(@"(?<range>[\w\d\-]{1,20}?)='[^']*'|(?<range>[\w\d\-]{1,20})=""[^""]*""|(?<range>[\w\d\-]{1,20})=[\w\d\-]{1,20}");
            HTMLAttrValRegex = new Regex(@"[\w\d\-]{1,20}?=(?<range>'[^']*')|[\w\d\-]{1,20}=(?<range>""[^""]*"")|[\w\d\-]{1,20}=(?<range>[\w\d\-]{1,20})");
            HTMLEntityRegex = new Regex(@"\&(amp|gt|lt|nbsp|quot|apos|copy|reg|#[0-9]{1,8}|#x[0-9a-f]{1,8});",RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// Highlights Xml code
        /// </summary>
        /// <param name="range"></param>
        void XmlSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "<!--^-->";
            range.tb.LeftBracket = '<';
            range.tb.RightBracket = '>';
            range.tb.LeftBracket2 = '(';
            range.tb.RightBracket2 = ')';
            //clear style of changed range
            range.ClearStyle(KeywordStyle, CommentStyle, TagBracketStyle, TagNameStyle, AttributeStyle, AttributeValueStyle, HtmlEntityStyle);
            //
            if (HTMLTagRegex == null)
                InitHTMLRegex();
            //comment highlighting
            range.SetStyle(CommentStyle, HTMLCommentRegex1);
            range.SetStyle(CommentStyle, HTMLCommentRegex2);
            //tag brackets highlighting
            range.SetStyle(TagBracketStyle, HTMLTagRegex);
            //tag name
            range.SetStyle(TagNameStyle, HTMLTagNameRegex);
            //end of tag
            range.SetStyle(TagNameStyle, HTMLEndTagRegex);
            //attributes
            range.SetStyle(AttributeStyle, HTMLAttrRegex);
            //attribute values
            range.SetStyle(AttributeValueStyle, HTMLAttrValRegex);
            //html entity
            range.SetStyle(HtmlEntityStyle, HTMLEntityRegex);
            range.SetStyle(TagBracketStyle, @"\?[a-zA-Z_\d]*\b", RegexOptions.IgnoreCase);
           
            XmlFold(range.tb);
        }
        private static Regex xmlfoldregex = new Regex(@"<(?<range>/?\w+)\s[^>]*?[^/]>|<(?<range>/?\w+)\s*>", RegexOptions.Singleline);
        void XmlFold(FastColoredTextBox fctb)
        {
            try
            {
                fctb.Range.ClearFoldingMarkers();
                //
                var stack = new Stack<Tag>();
                var id = 0;
                //extract opening and closing tags (exclude open-close tags: <TAG/>)
                foreach (var r in fctb.Range.GetRanges(xmlfoldregex))
                {
                    var tagName = r.Text;
                    var iLine = r.Start.iLine;
                    //if it is opening tag...
                    if (tagName[0] != '/')
                    {
                        // ...push into stack
                        var tag = new Tag { Name = tagName, id = id++, startLine = r.Start.iLine };
                        stack.Push(tag);
                        // if this line has no markers - set marker
                        if (string.IsNullOrEmpty(fctb[iLine].FoldingStartMarker))
                            fctb[iLine].FoldingStartMarker = tag.Marker;
                    }
                    else
                    {
                        //if it is closing tag - pop from stack
                        var tag = stack.Pop();
                        //compare line number
                        if (iLine == tag.startLine)
                        {
                            //remove marker, because same line can not be folding
                            if (fctb[iLine].FoldingStartMarker == tag.Marker)//was it our marker?
                                fctb[iLine].FoldingStartMarker = null;
                        }
                        else
                        {
                            //set end folding marker
                            if (string.IsNullOrEmpty(fctb[iLine].FoldingEndMarker))
                                fctb[iLine].FoldingEndMarker = tag.Marker;
                        }
                    }
                }
            }
            catch (Exception) { }
        }
        void PythonSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "#";
            r.tb.LeftBracket = '(';
            r.tb.RightBracket = ')';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, NumberStyle, StringStyle, ClassNameStyle2, KeywordStyle, KeywordStyle2, CharStyle);
            r.SetStyle(CommentTagStyle, "(\"\"\".*?\"\"\")|(.*\"\"\")|(\'\'\'.*?\'\'\')|(.*\'\'\')", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexOptions.Multiline);
            r.SetStyle(CommentStyle, "#.*$", RegexOptions.Multiline);
            r.SetStyle(NumberStyle, "\b\\d+[\\.]?\\d*([eE]\\-?\\d+)?[lLdDfF]?\b|\b0x[a-fA-F\\d]+\b");
            r.SetStyle(StringStyle, "\".*?[^\\\\]\"|\"\"|\'.*?[^\\\\]\'|\'\'", RegexOptions.Multiline);
            r.SetStyle(ClassNameStyle, @"\b(class)\s+(?<range>\w+?)\b");
            r.SetStyle(ClassNameStyle2, @"\b(def)\s+(?<range>\w+?)\b");
            r.SetStyle(KeywordStyle, @"\b(and|del|from|not|while|as|elif|global|or|with|assert|else|if|pass|yield|break|except|import|print|class|exec|nonlocal|in|raise|continue|finally|is|return|def|for|lambda|try)\b");
            r.SetStyle(KeywordStyle2, @"\b(int|id|callable|dict|open|all|vars|object|iter|enumerate|sorted|property|super|classmethod|tuple|compile|YnoteSettingsBasestring|map|range|ord|isinstance|long|float|format|str|type|hasattr|max|len|repr|getattr|list)\b");
            r.SetStyle(CharStyle, @"\!|\:|\+|=|\-|\*|\@");
            r.ClearFoldingMarkers();
            PythonFold(r.tb);
        }
        void PythonFold(FastColoredTextBox fctb)
        {
            //delete all markers
            fctb.Range.ClearFoldingMarkers();

            var currentIndent = 0;
            var lastNonEmptyLine = 0;

            for (int i = 0; i < fctb.LinesCount; i++)
            {
                var line = fctb[i];
                var spacesCount = line.StartSpacesCount;
                if (spacesCount == line.Count) //empty line
                    continue;

                if (currentIndent < spacesCount)
                    //append start folding marker
                    fctb[lastNonEmptyLine].FoldingStartMarker = "m" + currentIndent;
                else
                    if (currentIndent > spacesCount)
                        //append end folding marker
                        fctb[lastNonEmptyLine].FoldingEndMarker = "m" + spacesCount;

                currentIndent = spacesCount;
                lastNonEmptyLine = i;
            }
        }
        void FSharpSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "//";
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle,StringStyle, KeywordStyle, KeywordStyle2);
            r.SetStyle(CommentStyle, "//.*$");
            r.SetStyle(CommentStyle, @"(\(\*.*?\*\))|(\(\*.*)");
            r.SetStyle(StringStyle, @"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'");
            r.SetStyle(KeywordStyle, @"\b(and|as|begin|do|done|val|stdin|downto|else|mutable|yield||end|exception|for|fun|function|in|if|let|match|module|not|open|of|prefix|raise|rec|struct|then|to|try|type|while|with|override|int|float|ushort|uint|long|byte|sbyte|bool|string|char)\b");
            r.SetStyle(KeywordStyle2, @"\b(true|false)\b");
            r.SetStyle(NumberStyle, @"\b\\d+[\\.]?\\d*([eE]\\-?\\d+)?[lLdDfF]?\b|\b0x[a-fA-F\\d]+\b");
        }
        /// <summary>
        /// Highlight INI Syntax
        /// </summary>
        /// <param name="r"></param>
        void INISyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = ";";
            range.ClearStyle(CommentStyle, KeywordStyle2, StringStyle,NumberStyle, CharStyle);
            range.SetStyle(CommentStyle, @"\;.*$", RegexOptions.Multiline);
            range.SetStyle(KeywordStyle2, @"\[.*?[^\\]\]");
            range.SetStyle(StringStyle, "\".*?[^\\\\]\"|\"\"|\'.*?[^\\\\]\'|\'\'");
            range.SetStyle(NumberStyle, "\b\\d+[\\.]?\\d*([eE]\\-?\\d+)?[lLdDfF]?\b|\b0x[a-fA-F\\d]+\b");
            range.SetStyle(CharStyle, @"\*|\,|\:,\?|\@|\!");
            range.ClearFoldingMarkers();
            foreach (var r in range.GetRangesByLines(@"^\[\w+\]$", RegexOptions.None))
            {
                if (r.Start.iLine > 0) r.tb[r.Start.iLine - 1].FoldingEndMarker = "section";
                r.tb[r.Start.iLine].FoldingStartMarker = "section";
            }
        }
        /// <summary>
        /// Lua Syntax Highlight
        /// </summary>
        /// <param name="r"></param>
        void LuaSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "--";
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, KeywordStyle, KeywordStyle2, StringStyle, NumberStyle, CharStyle);
            r.SetStyle(CommentStyle, @"--.*$", RegexOptions.Multiline);
            r.SetStyle(CommentStyle, @"\-\-\[\[.+?\-\-\]\]", RegexOptions.Singleline | RegexOptions.RightToLeft);
            r.SetStyle(KeywordStyle, @"\b(and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b", RegexOptions.IgnoreCase);
            r.SetStyle(KeywordStyle2, @"\b(math|_VERSION|assert|collectgarbage|dofile|error|gcinfo|loadfile|loadstring|print|println|tonumber|tostring|type|unpack|_ALERT|_ERRORMESSAGE|_INPUT|_PROMPT|_OUPUT|_STDERR|_STDIN|_STDOUT|call|dostring|foreach|foreachi|getn|globals|newtype|rawget|rawset|require|math|sort|tremove|_G|getfenv|getmetatable|ipairs|loadlib|next|pairs|pcall|rawegal|setfenv|setmetatable|xpcall|string|table|coroutine|io|os|debug)\b", RegexOptions.IgnoreCase);
            r.SetStyle(StringStyle, "\".*?[^\\\\]\"|\"\"|\'.*?[^\\\\]\'|\'\'");
            r.SetStyle(NumberStyle, @"\b\\d+[\\.]?\\d*([eE]\\-?\\d+)?[lLdDfF]?\b|\b0x[a-fA-F\\d]+\b");
            r.SetStyle(CharStyle, @"\[|\]|\*|\?|\(|\)|\^|\!|\;|\,|\.|\:");
            r.ClearFoldingMarkers();
            r.SetFoldingMarkers(@"function", @"end", RegexOptions.IgnoreCase);
        }
        void RubySyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "#";
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, KeywordStyle, StringStyle, NumberStyle, CharStyle, ClassNameStyle2);
            r.SetStyle(CommentStyle, @"#.*$", RegexOptions.Multiline);
            r.SetStyle(KeywordStyle, @"\b(__FILE__|__LINE__|BEGIN|END|alias|and|begin|break|case|class|def|defined|do|else|elsif|end|ensure|false|for|if|in|module|next|nil|not|or|redo|rescue|retry|return|super|then|true|undef|unless|until|when|while|yield|block_given|catch|class|extend|loop|new|raise|require|throw)\b");
            r.SetStyle(CommentStyle, @"(=begin.*?=end)|(.*=end)", RegexOptions.IgnoreCase | RegexOptions.RightToLeft | RegexOptions.Singleline);
            r.SetStyle(ClassNameStyle, @"\b(class)\s+(?<range>\w+?)\b");
            r.SetStyle(ClassNameStyle2, @"\b(def)\s+(?<range>\w+?)\b");
            r.SetStyle(VariableStyle, @"\$[a-zA-Z_\d]*\b", RegexCompiledOption);
            r.SetStyle(StringStyle, "\".*?[^\\\\]\"|\"\"|\'.*?[^\\\\]\'|\'\'");
            r.SetStyle(NumberStyle, @"\b\\d+[\\.]?\\d*([eE]\\-?\\d+)?[lLdDfF]?\b|\b0x[a-fA-F\\d]+\b");
            r.SetStyle(CharStyle, @"\[|\]|\*|\?|\(|\)|\^|\!|\;|\,|\.|\:");
            PythonFold(r.tb);
        }
        void JSONSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = null;
            r.tb.LeftBracket = '(';
            r.tb.RightBracket = ')';
            r.tb.LeftBracket2 = '{';
            r.tb.RightBracket2 = '}';
            r.ClearStyle(KeywordStyle3, StringStyle, NumberStyle, KeywordStyle);
            r.SetStyle(StringStyle, "\".*?[^\\\\]\"|\"\"|\'.*?[^\\\\]\'|\'\'");
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?\b");
            r.SetStyle(KeywordStyle3, "\\W|_");
            r.SetStyle(KeywordStyle, "true|false", RegexOptions.IgnoreCase);
            r.ClearFoldingMarkers();
            r.SetFoldingMarkers("{", "}");
        }
        void LispSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = ";";
            r.ClearStyle(CommentStyle,StringStyle, KeywordStyle,ClassNameStyle2,NumberStyle, CharStyle);
            r.SetStyle(CommentStyle, @"\;.*$", RegexOptions.Multiline);
            r.SetStyle(StringStyle, @"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption);
            r.SetStyle(KeywordStyle, @"\b(and|eval|else|nil|if|lambda|or|set|defun)\b");
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*\b", RegexCompiledOption);
            r.SetStyle(CharStyle, @"\;|\!|#|\:|\*|\&|\@|\(|\)|\-|=|\?|\\");
            foreach (Range found in r.tb.GetRanges(@"\b(defun|DEFUN)\s+(?<range>\w+)\b"))
                r.SetStyle(ClassNameStyle2, @"\b" + found.Text + @"\b");
        }
        /// <summary>
        /// Perl Syntax Highlight
        /// </summary>
        /// <param name="r"></param>
        void PerlSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "#";
            r.tb.LeftBracket = '(';
            r.tb.RightBracket = ')';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, StringStyle,VariableStyle, KeywordStyle,KeywordStyle2,KeywordStyle3, NumberStyle);
            r.SetStyle(StringStyle, @"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption);
            r.SetStyle(CommentStyle, "#.*$", RegexOptions.Multiline);
            r.SetStyle(CommentStyle, @"(=begin.*?=cut)|(.*=cut)", RegexOptions.IgnoreCase | RegexOptions.RightToLeft | RegexOptions.Singleline);
            r.SetStyle(VariableStyle, @"\$[a-zA-Z_\d]*\b", RegexCompiledOption);
            r.SetStyle(KeywordStyle, @"\b(use|my|last|scalar|for|foreach|elsif|require|package|continue|goto|next|until|unless|while|our|sub|if|no|else|local|return)\b");
            r.SetStyle(KeywordStyle2, @"\b(bless|close|closedir|die|eval|exit|grep|map|open|opendir|print|return|splice|split|sysopen|warn|do|each|values|BEGIN|CORE|DESTROY|END|STDERR|STDIN|STDOUT|abs|accept|alarm|and|atan2|bind|binmode|caller|chdir|chmod|chomp|chop|chown|chr|chroot|cmp|connect|cos|crypt|dbmclose|dbmopen|default|defined|delete|dump|endgrent|endhostent|endnetent|endprotoent|endpwent|endservent|eof|eq|exec|exists|exp|fcntl|fileno|flock|fork|formline|ge|getc|getgrent|getgrgid|getgrnam|gethostbyad|gethostbyna|gethostent|getlogin|getnetbyadd|getnetbynam|getnetent|getpeername|getpgrp|getppid|getpriority|getprotobyn|getprotobyn|getprotoent|getpwent|getpwnam|getpwuid|getservbyna|getservbypo|getservent|getsockname|getsockopt|glob|gmtime|gt|hex|import|index|int|ioctl|join|keys|kill|lc|lcfirst|le|length|link|listen|localtime|log|lstat|lt|m|mkdir|msgctl|msgget|msgrcv|msgsnd|ne|new|ne|not|oct|or|ord|pack|pipe|pop|pos|printf|q|qq|quotemeta|qw|qx|rand|read|readdir|readlink|readpipe|recv|ref|rename|reset|reverse|rewinddir|rindex|rmdir|s|seek|seekdir|select|semctl|semget|semop|send|setgrent|sethostent|setnetent|setpgrp|setpriority|setprotoent|setpwent|setservent|setsockopt|shift|shmctl|shmget|shmread|shmwrite|shutdown|sin|sleep|socket|socketpair|sort|split|sprintf|sqrt|srand|stat|study|substr|switch|symlink|syscall|sysread|system|system|syswrite|tell|telldir|time|times|tr|truncate|uc|ucfirst|umask|undef|unlink|unpack|unshift|untie|utime|vec|wait|waitpid|wantarray|write|x|xor|y)\b");
            r.SetStyle(KeywordStyle3, @"\b(\-a|\-e|\-b|\-c|\-d|\-k|\-f|\-g|\-l|\-m|\-o|\-p|\-r|\-s|\-t|\-u|\-w|\-x|\-z)\b", RegexOptions.IgnoreCase);
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*\b", RegexCompiledOption);
            r.ClearFoldingMarkers();
            r.SetFoldingMarkers("=begin", "=cut");
            r.SetFoldingMarkers("{", "}");
        }
        Regex PHPStringRegex, PHPNumberRegex, PHPCommentRegex1, PHPCommentRegex2, PHPCommentRegex3, PHPVarRegex, PHPKeywordRegex1, PHPKeywordRegex2, PHPKeywordRegex3;

        void InitPHPRegex()
        {
            PHPStringRegex = new Regex(@"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption);
            PHPNumberRegex = new Regex(@"\b\d+[\.]?\d*\b", RegexCompiledOption);
            PHPCommentRegex1 = new Regex(@"(//|#).*$", RegexOptions.Multiline | RegexCompiledOption);
            PHPCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption);
            PHPCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption);
            PHPVarRegex = new Regex(@"\$[a-zA-Z_\d]*\b", RegexCompiledOption);
            PHPKeywordRegex1 = new Regex(@"\b(die|echo|empty|define|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset)\b", RegexCompiledOption);
            PHPKeywordRegex2 = new Regex(@"\b(abstract|and|array|as|break|true|false|case|catch|cfunction|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|instanceof|interface|namespace|new|or|private|protected|public|static|switch|throw|try|use|var|while|xor)\b", RegexCompiledOption);
            PHPKeywordRegex3 = new Regex(@"__CLASS__|__DIR__|__FILE__|__LINE__|__FUNCTION__|__METHOD__|__NAMESPACE__", RegexCompiledOption);
        }

        /// <summary>
        /// Highlights PHP code
        /// </summary>
        /// <param name="range"></param>
        void PHPSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "//";
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '[';
            range.tb.RightBracket2 = ']';
            //clear style of changed range
            range.ClearStyle(CommentStyle, NumberStyle, VariableStyle, KeywordStyle2, KeywordStyle, KeywordStyle3, CharStyle);
            //
            if (PHPStringRegex == null)
                InitPHPRegex();
            //comment highlighting
            range.SetStyle(CommentStyle, PHPCommentRegex1);
            range.SetStyle(CommentStyle, PHPCommentRegex2);
            range.SetStyle(CommentStyle, PHPCommentRegex3);
            //string highlighting
            range.SetStyle(StringStyle, PHPStringRegex);
            //number highlighting
            range.SetStyle(NumberStyle, PHPNumberRegex);
            //var highlighting
            range.SetStyle(VariableStyle, PHPVarRegex);
            //keyword highlighting
            range.SetStyle(KeywordStyle2, PHPKeywordRegex1);
            range.SetStyle(KeywordStyle, PHPKeywordRegex2);
            range.SetStyle(KeywordStyle3, PHPKeywordRegex3);
            range.SetStyle(CharStyle, @">|\*|-|=|\+|\!|<|\^|\?");
            //clear folding markers
            range.ClearFoldingMarkers();
            //set folding markers
            range.SetFoldingMarkers("{", "}");//allow to collapse brackets block
            range.SetFoldingMarkers(@"/\*", @"\*/");//allow to collapse comment block
            range.SetFoldingMarkers(@"<\?", @"/?>");
        }
        Regex CSharpStringRegex, CSharpCommentRegex1, CSharpCommentRegex2, CSharpCommentRegex3,CsharpFunctionRegex, CSharpNumberRegex, CSharpAttributeRegex, CSharpClassNameRegex, CSharpKeywordRegex, CSharpKeywordRegex2;

        void InitCSharpRegex()
        {
            CSharpStringRegex = new Regex(@"""""|@""""|''|@"".*?""|(?<!@)(?<range>"".*?[^\\]"")|'.*?[^\\]'", RegexCompiledOption);
            CSharpCommentRegex1 = new Regex(@"//.*$", RegexOptions.Multiline | RegexCompiledOption);
            CSharpCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption);
            CSharpCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption);
            CSharpNumberRegex = new Regex(@"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b", RegexCompiledOption);
            CSharpAttributeRegex = new Regex(@"^\s*(?<range>\[.+?\])\s*$", RegexOptions.Multiline | RegexCompiledOption);
            CSharpClassNameRegex = new Regex(@"\b(class|struct|enum|interface)\s+(?<range>\w+?)\b", RegexCompiledOption);
            CSharpKeywordRegex = new Regex(@"\b(abstract|as|base|using|break|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|interface|internal|is|this|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|struct|switch|throw|true|try|typeof|unchecked|unsafe|virtual|volatile|while|add|alias|ascending|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b|#region\b|#endregion\b", RegexCompiledOption);
            CSharpKeywordRegex2 = new Regex(@"\b(void|bool|string|int|double|float|byte|uint|ushort|ulong)\b");
            CsharpFunctionRegex = new Regex(@"\b(void|int|bool|string|uint|ushort|ulong|byte)\s+(?<range>\w+?)\b");
        }
        private void CSharpSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "//";
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '[';
            range.tb.RightBracket2 = ']';
            //clear style of changed range
            range.ClearStyle(CommentStyle, StringStyle, NumberStyle, AttributeStyle, ClassNameStyle, KeywordStyle);
            //
            if (CSharpStringRegex == null)
                InitCSharpRegex();
            //comment highlighting
            range.SetStyle(CommentStyle, CSharpCommentRegex1);
            range.SetStyle(CommentStyle, CSharpCommentRegex2);
            range.SetStyle(CommentStyle, CSharpCommentRegex3);
            //string highlighting
            range.SetStyle(StringStyle, CSharpStringRegex);
            //number highlighting
            range.SetStyle(NumberStyle, CSharpNumberRegex);
            //attribute highlighting
            range.SetStyle(AttributeStyle, CSharpAttributeRegex);
            //class name highlighting
            range.SetStyle(ClassNameStyle, CSharpClassNameRegex);
            //funtion highlight
            range.SetStyle(ClassNameStyle2, CsharpFunctionRegex);
            //keyword highlighting
            range.SetStyle(KeywordStyle, CSharpKeywordRegex);
            //keywordstyle2
            range.SetStyle(KeywordStyle2, CSharpKeywordRegex2);
            range.ClearFoldingMarkers();
            range.SetFoldingMarkers("{", "}");//allow to collapse brackets block
            range.SetFoldingMarkers("#region", "#endregion");
            range.SetFoldingMarkers(@"/\*", @"\*/");//allow to collapse comment block
        }
        Regex JScriptStringRegex,JScriptFunctionRegex,JScriptFunctionRegex2, JScriptCommentRegex1, JScriptCommentRegex2, JScriptCommentRegex3, JScriptNumberRegex, JScriptKeywordRegex;

        void InitJScriptRegex()
        {
            JScriptStringRegex = new Regex(@"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption);
            JScriptCommentRegex1 = new Regex(@"//.*$", RegexOptions.Multiline | RegexCompiledOption);
            JScriptCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption);
            JScriptCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption);
            JScriptNumberRegex = new Regex(@"\b\d+[\.]?\d*([eE]\-?\d+)?[lLdDfF]?\b|\b0x[a-fA-F\d]+\b", RegexCompiledOption);
            JScriptKeywordRegex = new Regex(@"\b(true|false|break|case|catch|const|continue|default|delete|do|else|export|for|function|if|in|instanceof|new|null|return|switch|this|throw|try|var|void|while|with|typeof)\b", RegexCompiledOption);
            JScriptFunctionRegex = new Regex(@"\b(function)\s+(?<range>\w+?)\b");
            JScriptFunctionRegex2 = new Regex(@"\b(var)\s+(?<range>\w+?)\b");
        }

        /// <summary>
        /// Highlights JavaScript code
        /// </summary>
        /// <param name="range"></param>
        void JScriptSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "//";
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '[';
            range.tb.RightBracket2 = ']';
            //clear style of changed range
            range.ClearStyle(CommentStyle, StringStyle, NumberStyle, KeywordStyle, CharStyle);
            //
            if (JScriptStringRegex == null)
                InitJScriptRegex();
            //comment highlighting
            range.SetStyle(CommentStyle, JScriptCommentRegex1);
            range.SetStyle(CommentStyle, JScriptCommentRegex2);
            range.SetStyle(CommentStyle, JScriptCommentRegex3);
            //string highlighting
            range.SetStyle(StringStyle, JScriptStringRegex);
            //number highlighting
            range.SetStyle(NumberStyle, JScriptNumberRegex);
            range.SetStyle(ClassNameStyle, JScriptFunctionRegex);
            range.SetStyle(ClassNameStyle2, JScriptFunctionRegex2);
            //keyword highlighting
            range.SetStyle(KeywordStyle, JScriptKeywordRegex);
            range.SetStyle(CharStyle, @"\;|\,|<|>|-|\$");
            //clear folding markers
            range.ClearFoldingMarkers();
            //set folding markers
            range.SetFoldingMarkers("{", "}");//allow to collapse brackets block
            range.SetFoldingMarkers(@"/\*", @"\*/");//allow to collapse comment block
        }

        /// <summary>
        /// Highlights HTML code
        /// </summary>
        /// <param name="range"></param>
        void HTMLSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "<!--";
            range.tb.LeftBracket = '<';
            range.tb.RightBracket = '>';
            range.tb.LeftBracket2 = '(';
            range.tb.RightBracket2 = ')';
            //clear style of changed range
            range.ClearStyle(CommentStyle, TagBracketStyle, TagNameStyle, AttributeStyle, AttributeValueStyle, HtmlEntityStyle);
            //
            if (HTMLTagRegex == null)
                InitHTMLRegex();
            //comment highlighting
            range.SetStyle(CommentStyle, HTMLCommentRegex1);
            range.SetStyle(CommentStyle, HTMLCommentRegex2);
            //tag brackets highlighting
            range.SetStyle(TagBracketStyle, HTMLTagRegex);
            //tag name
            range.SetStyle(TagNameStyle, HTMLTagNameRegex);
            //end of tag
            range.SetStyle(TagNameStyle, HTMLEndTagRegex);
            //attributes
            range.SetStyle(AttributeStyle, HTMLAttrRegex);
            //attribute values
            range.SetStyle(AttributeValueStyle, HTMLAttrValRegex);
            //html entity
            range.SetStyle(HtmlEntityStyle, HTMLEntityRegex);

            //clear folding markers
            range.ClearFoldingMarkers();
            //set folding markers
            range.SetFoldingMarkers("<head", "</head>", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers("<body", "</body>", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers("<table", "</table>", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers("<form", "</form>", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers("<div", "</div>", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers("<script", "</script>", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers("<tr", "</tr>", RegexOptions.IgnoreCase);
        }

        Regex VBStringRegex, VBCommentRegex, VBNumberRegex, VBClassNameRegex, VBKeywordRegex;

        void InitVBRegex()
        {
            VBStringRegex = new Regex(@"""""|"".*?[^\\]""", RegexCompiledOption);
            VBCommentRegex = new Regex(@"'.*$", RegexOptions.Multiline | RegexCompiledOption);
            VBNumberRegex = new Regex(@"\b\d+[\.]?\d*([eE]\-?\d+)?\b", RegexCompiledOption);
            VBClassNameRegex = new Regex(@"\b(Class|Structure|Enum|Interface)[ ]+(?<range>\w+?)\b", RegexOptions.IgnoreCase | RegexCompiledOption);
            VBKeywordRegex = new Regex(@"\b(AddHandler|AddressOf|Alias|And|AndAlso|As|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDbl|CDec|Char|CInt|Class|CLng|CObj|Const|Continue|CSByte|CShort|CSng|CStr|CType|CUInt|CULng|CUShort|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|False|Finally|For|Friend|Function|Get|GetType|GetXMLNamespace|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mod|Module|MustInherit|MustOverride|MyYnoteSettingsBase|MyClass|Namespace|Narrowing|New|Next|Not|Nothing|NotInheritable|NotOverridable|Object|Of|On|Operator|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Partial|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|REM|RemoveHandler|Resume|Return|SByte|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|True|Try|TryCast|TypeOf|UInteger|ULong|UShort|Using|Variant|Wend|When|While|Widening|With|WithEvents|WriteOnly|Xor|Region)\b|(#Const|#Else|#ElseIf|#End|#If|#Region)\b", RegexOptions.IgnoreCase | RegexCompiledOption);
        }

        /// <summary>
        /// Highlights VB code
        /// </summary>
        /// <param name="range"></param>
        private void VBSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "'";
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '\x0';
            range.tb.RightBracket2 = '\x0';
            //clear style of changed range
            range.ClearStyle(StringStyle, CommentStyle, NumberStyle, ClassNameStyle, KeywordStyle);
            //
            if (VBStringRegex == null)
                InitVBRegex();
            //string highlighting
            range.SetStyle(StringStyle, VBStringRegex);
            //comment highlighting
            range.SetStyle(CommentStyle, VBCommentRegex);
            //number highlighting
            range.SetStyle(NumberStyle, VBNumberRegex);
            //class name highlighting
            range.SetStyle(ClassNameStyle, VBClassNameRegex);
            //keyword highlighting
            range.SetStyle(KeywordStyle, VBKeywordRegex);

            //clear folding markers
            range.ClearFoldingMarkers();
            //set folding markers
            range.SetFoldingMarkers(@"#Region\b", @"#End\s+Region\b", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers(@"\b(Class|Property|Enum|Structure|Interface)[ \t]+\S+", @"\bEnd (Class|Property|Enum|Structure|Interface)\b", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers(@"^\s*(?<range>While)[ \t]+\S+", @"^\s*(?<range>End While)\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            range.SetFoldingMarkers(@"\b(Sub|Function)[ \t]+[^\s']+", @"\bEnd (Sub|Function)\b", RegexOptions.IgnoreCase);//this declared separately because Sub and Function can be unclosed
            range.SetFoldingMarkers(@"(\r|\n|^)[ \t]*(?<range>Get|Set)[ \t]*(\r|\n|$)", @"\bEnd (Get|Set)\b", RegexOptions.IgnoreCase);
            range.SetFoldingMarkers(@"^\s*(?<range>For|For\s+Each)\b", @"^\s*(?<range>Next)\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            range.SetFoldingMarkers(@"^\s*(?<range>Do)\b", @"^\s*(?<range>Loop)\b", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        }
        Regex SQLStringRegex, SQLNumberRegex, SQLCommentRegex1, SQLCommentRegex2, SQLCommentRegex3, SQLVarRegex, SQLStatementsRegex, SQLKeywordsRegex, SQLFunctionsRegex, SQLTypesRegex;

        void InitSQLRegex()
        {
            SQLStringRegex = new Regex(@"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption);
            SQLNumberRegex = new Regex(@"\b\d+[\.]?\d*([eE]\-?\d+)?\b", RegexCompiledOption);
            SQLCommentRegex1 = new Regex(@"--.*$", RegexOptions.Multiline | RegexCompiledOption);
            SQLCommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption);
            SQLCommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption);
            SQLVarRegex = new Regex(@"@[a-zA-Z_\d]*\b", RegexCompiledOption);
            SQLStatementsRegex = new Regex(@"\b(ALTER APPLICATION ROLE|ALTER ASSEMBLY|ALTER ASYMMETRIC KEY|ALTER AUTHORIZATION|ALTER BROKER PRIORITY|ALTER CERTIFICATE|ALTER CREDENTIAL|ALTER CRYPTOGRAPHIC PROVIDER|ALTER DATAYnoteSettingsBase|ALTER DATAYnoteSettingsBase AUDIT SPECIFICATION|ALTER DATAYnoteSettingsBase ENCRYPTION KEY|ALTER ENDPOINT|ALTER EVENT SESSION|ALTER FULLTEXT CATALOG|ALTER FULLTEXT INDEX|ALTER FULLTEXT STOPLIST|ALTER FUNCTION|ALTER INDEX|ALTER LOGIN|ALTER MASTER KEY|ALTER MESSAGE TYPE|ALTER PARTITION FUNCTION|ALTER PARTITION SCHEME|ALTER PROCEDURE|ALTER QUEUE|ALTER REMOTE SERVICE BINDING|ALTER RESOURCE GOVERNOR|ALTER RESOURCE POOL|ALTER ROLE|ALTER ROUTE|ALTER SCHEMA|ALTER SERVER AUDIT|ALTER SERVER AUDIT SPECIFICATION|ALTER SERVICE|ALTER SERVICE MASTER KEY|ALTER SYMMETRIC KEY|ALTER TABLE|ALTER TRIGGER|ALTER USER|ALTER VIEW|ALTER WORKLOAD GROUP|ALTER XML SCHEMA COLLECTION|BULK INSERT|CREATE AGGREGATE|CREATE APPLICATION ROLE|CREATE ASSEMBLY|CREATE ASYMMETRIC KEY|CREATE BROKER PRIORITY|CREATE CERTIFICATE|CREATE CONTRACT|CREATE CREDENTIAL|CREATE CRYPTOGRAPHIC PROVIDER|CREATE DATAYnoteSettingsBase|CREATE DATAYnoteSettingsBase AUDIT SPECIFICATION|CREATE DATAYnoteSettingsBase ENCRYPTION KEY|CREATE DEFAULT|CREATE ENDPOINT|CREATE EVENT NOTIFICATION|CREATE EVENT SESSION|CREATE FULLTEXT CATALOG|CREATE FULLTEXT INDEX|CREATE FULLTEXT STOPLIST|CREATE FUNCTION|CREATE INDEX|CREATE LOGIN|CREATE MASTER KEY|CREATE MESSAGE TYPE|CREATE PARTITION FUNCTION|CREATE PARTITION SCHEME|CREATE PROCEDURE|CREATE QUEUE|CREATE REMOTE SERVICE BINDING|CREATE RESOURCE POOL|CREATE ROLE|CREATE ROUTE|CREATE RULE|CREATE SCHEMA|CREATE SERVER AUDIT|CREATE SERVER AUDIT SPECIFICATION|CREATE SERVICE|CREATE SPATIAL INDEX|CREATE STATISTICS|CREATE SYMMETRIC KEY|CREATE SYNONYM|CREATE TABLE|CREATE TRIGGER|CREATE TYPE|CREATE USER|CREATE VIEW|CREATE WORKLOAD GROUP|CREATE XML INDEX|CREATE XML SCHEMA COLLECTION|DELETE|DISABLE TRIGGER|DROP AGGREGATE|DROP APPLICATION ROLE|DROP ASSEMBLY|DROP ASYMMETRIC KEY|DROP BROKER PRIORITY|DROP CERTIFICATE|DROP CONTRACT|DROP CREDENTIAL|DROP CRYPTOGRAPHIC PROVIDER|DROP DATAYnoteSettingsBase|DROP DATAYnoteSettingsBase AUDIT SPECIFICATION|DROP DATAYnoteSettingsBase ENCRYPTION KEY|DROP DEFAULT|DROP ENDPOINT|DROP EVENT NOTIFICATION|DROP EVENT SESSION|DROP FULLTEXT CATALOG|DROP FULLTEXT INDEX|DROP FULLTEXT STOPLIST|DROP FUNCTION|DROP INDEX|DROP LOGIN|DROP MASTER KEY|DROP MESSAGE TYPE|DROP PARTITION FUNCTION|DROP PARTITION SCHEME|DROP PROCEDURE|DROP QUEUE|DROP REMOTE SERVICE BINDING|DROP RESOURCE POOL|DROP ROLE|DROP ROUTE|DROP RULE|DROP SCHEMA|DROP SERVER AUDIT|DROP SERVER AUDIT SPECIFICATION|DROP SERVICE|DROP SIGNATURE|DROP STATISTICS|DROP SYMMETRIC KEY|DROP SYNONYM|DROP TABLE|DROP TRIGGER|DROP TYPE|DROP USER|DROP VIEW|DROP WORKLOAD GROUP|DROP XML SCHEMA COLLECTION|ENABLE TRIGGER|EXEC|EXECUTE|FROM|INSERT|MERGE|OPTION|OUTPUT|SELECT|TOP|TRUNCATE TABLE|UPDATE|UPDATE STATISTICS|WHERE|WITH)\b", RegexOptions.IgnoreCase | RegexCompiledOption);
            SQLKeywordsRegex = new Regex(@"\b(ADD|ALL|AND|ANY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BY|CASCADE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTINUE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURSOR|DATAYnoteSettingsBase|DBCC|DEALLOCATE|DECLARE|DEFAULT|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXISTS|EXIT|EXTERNAL|FETCH|FILE|FILLFACTOR|FOR|FOREIGN|FREETEXT|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITY_INSERT|IDENTITYCOL|IF|IN|INDEX|INNER|INTERSECT|INTO|IS|JOIN|KEY|KILL|LIKE|LINENO|LOAD|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|OF|OFF|OFFSETS|ON|OPEN|OR|ORDER|OUTER|OVER|PERCENT|PIVOT|PLAN|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVERT|REVOKE|ROLLBACK|ROWCOUNT|ROWGUIDCOL|RULE|SAVE|SCHEMA|SECURITYAUDIT|SET|SHUTDOWN|SOME|STATISTICS|TABLE|TABLESAMPLE|TEXTSIZE|THEN|TO|TRAN|TRANSACTION|TRIGGER|TSEQUAL|UNION|UNIQUE|UNPIVOT|UPDATETEXT|USE|USER|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHILE|WRITETEXT)\b", RegexOptions.IgnoreCase | RegexCompiledOption);
            SQLFunctionsRegex = new Regex(@"(@@CONNECTIONS|@@CPU_BUSY|@@CURSOR_ROWS|@@DATEFIRST|@@DATEFIRST|@@DBTS|@@ERROR|@@FETCH_STATUS|@@IDENTITY|@@IDLE|@@IO_BUSY|@@LANGID|@@LANGUAGE|@@LOCK_TIMEOUT|@@MAX_CONNECTIONS|@@MAX_PRECISION|@@NESTLEVEL|@@OPTIONS|@@PACKET_ERRORS|@@PROCID|@@REMSERVER|@@ROWCOUNT|@@SERVERNAME|@@SERVICENAME|@@SPID|@@TEXTSIZE|@@TRANCOUNT|@@VERSION)\b|\b(ABS|ACOS|APP_NAME|ASCII|ASIN|ASSEMBLYPROPERTY|AsymKey_ID|ASYMKEY_ID|asymkeyproperty|ASYMKEYPROPERTY|ATAN|ATN2|AVG|CASE|CAST|CEILING|Cert_ID|Cert_ID|CertProperty|CHAR|CHARINDEX|CHECKSUM_AGG|COALESCE|COL_LENGTH|COL_NAME|COLLATIONPROPERTY|COLLATIONPROPERTY|COLUMNPROPERTY|COLUMNS_UPDATED|COLUMNS_UPDATED|CONTAINSTABLE|CONVERT|COS|COT|COUNT|COUNT_BIG|CRYPT_GEN_RANDOM|CURRENT_TIMESTAMP|CURRENT_TIMESTAMP|CURRENT_USER|CURRENT_USER|CURSOR_STATUS|DATAYnoteSettingsBase_PRINCIPAL_ID|DATAYnoteSettingsBase_PRINCIPAL_ID|DATAYnoteSettingsBasePROPERTY|DATAYnoteSettingsBasePROPERTYEX|DATALENGTH|DATALENGTH|DATEADD|DATEDIFF|DATENAME|DATEPART|DAY|DB_ID|DB_NAME|DECRYPTBYASYMKEY|DECRYPTBYCERT|DECRYPTBYKEY|DECRYPTBYKEYAUTOASYMKEY|DECRYPTBYKEYAUTOCERT|DECRYPTBYPASSPHRASE|DEGREES|DENSE_RANK|DIFFERENCE|ENCRYPTBYASYMKEY|ENCRYPTBYCERT|ENCRYPTBYKEY|ENCRYPTBYPASSPHRASE|ERROR_LINE|ERROR_MESSAGE|ERROR_NUMBER|ERROR_PROCEDURE|ERROR_SEVERITY|ERROR_STATE|EVENTDATA|EXP|FILE_ID|FILE_IDEX|FILE_NAME|FILEGROUP_ID|FILEGROUP_NAME|FILEGROUPPROPERTY|FILEPROPERTY|FLOOR|fn_helpcollations|fn_listextendedproperty|fn_servershareddrives|fn_virtualfilestats|fn_virtualfilestats|FORMATMESSAGE|FREETEXTTABLE|FULLTEXTCATALOGPROPERTY|FULLTEXTSERVICEPROPERTY|GETANSINULL|GETDATE|GETUTCDATE|GROUPING|HAS_PERMS_BY_NAME|HOST_ID|HOST_NAME|IDENT_CURRENT|IDENT_CURRENT|IDENT_INCR|IDENT_INCR|IDENT_SEED|IDENTITY\(|INDEX_COL|INDEXKEY_PROPERTY|INDEXPROPERTY|IS_MEMBER|IS_OBJECTSIGNED|IS_SRVROLEMEMBER|ISDATE|ISDATE|ISNULL|ISNUMERIC|Key_GUID|Key_GUID|Key_ID|Key_ID|KEY_NAME|KEY_NAME|LEFT|LEN|LOG|LOG10|LOWER|LTRIM|MAX|MIN|MONTH|NCHAR|NEWID|NTILE|NULLIF|OBJECT_DEFINITION|OBJECT_ID|OBJECT_NAME|OBJECT_SCHEMA_NAME|OBJECTPROPERTY|OBJECTPROPERTYEX|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|ORIGINAL_LOGIN|ORIGINAL_LOGIN|PARSENAME|PATINDEX|PATINDEX|PERMISSIONS|PI|POWER|PUBLISHINGSERVERNAME|PWDCOMPARE|PWDENCRYPT|QUOTENAME|RADIANS|RAND|RANK|REPLACE|REPLICATE|REVERSE|RIGHT|ROUND|ROW_NUMBER|ROWCOUNT_BIG|RTRIM|SCHEMA_ID|SCHEMA_ID|SCHEMA_NAME|SCHEMA_NAME|SCOPE_IDENTITY|SERVERPROPERTY|SESSION_USER|SESSION_USER|SESSIONPROPERTY|SETUSER|SIGN|SignByAsymKey|SignByCert|SIN|SOUNDEX|SPACE|SQL_VARIANT_PROPERTY|SQRT|SQUARE|STATS_DATE|STDEV|STDEVP|STR|STUFF|SUBSTRING|SUM|SUSER_ID|SUSER_NAME|SUSER_SID|SUSER_SNAME|SWITCHOFFSET|SYMKEYPROPERTY|symkeyproperty|sys\.dm_db_index_physical_stats|sys\.fn_builtin_permissions|sys\.fn_my_permissions|SYSDATETIME|SYSDATETIMEOFFSET|SYSTEM_USER|SYSTEM_USER|SYSUTCDATETIME|TAN|TERTIARY_WEIGHTS|TEXTPTR|TODATETIMEOFFSET|TRIGGER_NESTLEVEL|TYPE_ID|TYPE_NAME|TYPEPROPERTY|UNICODE|UPDATE\(|UPPER|USER_ID|USER_NAME|USER_NAME|VAR|VARP|VerifySignedByAsymKey|VerifySignedByCert|XACT_STATE|YEAR)\b", RegexOptions.IgnoreCase | RegexCompiledOption);
            SQLTypesRegex = new Regex(@"\b(BIGINT|NUMERIC|BIT|SMALLINT|DECIMAL|SMALLMONEY|INT|TINYINT|MONEY|FLOAT|REAL|DATE|DATETIMEOFFSET|DATETIME2|SMALLDATETIME|DATETIME|TIME|CHAR|VARCHAR|TEXT|NCHAR|NVARCHAR|NTEXT|BINARY|VARBINARY|IMAGE|TIMESTAMP|HIERARCHYID|TABLE|UNIQUEIDENTIFIER|SQL_VARIANT|XML)\b", RegexOptions.IgnoreCase | RegexCompiledOption);

        }

        /// <summary>
        /// Highlights SQL code
        /// </summary>
        /// <param name="range"></param>
        private void SQLSyntaxHighlight(Range range)
        {
            range.tb.CommentPrefix = "--";
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '\x0';
            range.tb.RightBracket2 = '\x0';
            //clear style of changed range
            range.ClearStyle(CommentStyle, StringStyle, NumberStyle, TypesStyle, VariableStyle, FunctionsStyle, KeywordStyle);
            //
            if (SQLStringRegex == null)
                InitSQLRegex();
            //comment highlighting
            range.SetStyle(CommentStyle, SQLCommentRegex1);
            range.SetStyle(CommentStyle, SQLCommentRegex2);
            range.SetStyle(CommentStyle, SQLCommentRegex3);
            //string highlighting
            range.SetStyle(StringStyle, SQLStringRegex);
            //number highlighting
            range.SetStyle(NumberStyle, SQLNumberRegex);
            //types highlighting
            range.SetStyle(TypesStyle, SQLTypesRegex);
            //var highlighting
            range.SetStyle(VariableStyle, SQLVarRegex);
            //statements
            range.SetStyle(StatementsStyle, SQLStatementsRegex);
            //keywords
            range.SetStyle(KeywordStyle, SQLKeywordsRegex);
            //functions
            range.SetStyle(FunctionsStyle, SQLFunctionsRegex);

            //clear folding markers
            range.ClearFoldingMarkers();
            //set folding markers
            range.SetFoldingMarkers(@"\bBEGIN\b", @"\bEND\b", RegexOptions.IgnoreCase);//allow to collapse BEGIN..END blocks
            range.SetFoldingMarkers(@"/\*", @"\*/");//allow to collapse comment block
        }
        /// <summary>
        /// D Syntax Highlight
        /// </summary>
        /// <param name="r"></param>
        private void DSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "//";
            r.tb.LeftBracket = '(';
            r.tb.RightBracket = ')';
            r.tb.LeftBracket2 = '{';
            r.tb.RightBracket2 = '}';
            r.ClearStyle(CommentStyle, StringStyle, KeywordStyle, KeywordStyle2, KeywordStyle3);
            r.SetStyle(CommentStyle, @"//.*$");
            r.SetStyle(CommentStyle, new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption));
            r.SetStyle(CommentStyle, new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption));
            r.SetStyle(StringStyle, @"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption);
            r.SetStyle(KeywordStyle, @"\b(AL|AH|AX|EAX|BL|BH|BX|EBX|CL|CH|CX|ECX|DL|DH|DX|EDX|BP|EBP|module|this|SP|ESP|ref|DI|EDI|SI|ESI|ES|CS|SS|DS|GS|FS|CR0|CR2|CR3|CR4|DR0|DR1|DR2|DR3|DR6|DR7|TR3|TR4|TR5|TR6|TR7|ST|MM0|MM1|MM2|MM3|MM4|MM5|MM6|MM7|lock|rep|repe|repne|repnz|repz|offset|seg|__LOCAL_SIZE|near ptr|far ptr|byte ptr|short ptr|int ptr|word ptr|dword ptr|float ptr|double ptr|extended ptr|aaa|aad|aam|aas|adc|add|addpd|addps|addsd|addss|and|andnpd|andnps|andpd|andps|arpl|bound|bsf|bsr|bswap|bt|btc|alias|defined|import|btr|bts|call|cbw|cdq|clc|cld|clflush|cli|clts|cmc|cmova|cmovae|cmovb|cmovbe|cmovc|cmove|cmovg|cmovge|cmovl|cmovle|cmovna|cmovnae|cmovnb|cmovnbe|cmovnc|cmovne|cmovng|cmovnge|cmovnl|cmovnle|cmovno|cmovnp|cmovns|cmovnz|cmovo|cmovp|cmovpe|cmovpo|cmovs|cmovz|cmp|cmppd|cmpps|cmps|cmpsb|cmpsd|cmpss|cmpsw|cmpxch8b|cmpxchg|comisd|comiss|cpuid|cvtdq2pd|cvtdq2ps|cvtpd2dq|cvtpd2pi|cvtpd2ps|cvtpi2pd|cvtpi2ps|cvtps2dq|cvtps2pd|cvtps2pi|cvtsd2si|cvtsd2ss|cvtsi2sd|cvtsi2ss|cvtss2sd|cvtss2si|cvttpd2dq|cvttpd2pi|cvttps2dq|cvttps2pi|cvttsd2si|cvttss2si|cwd|cwde|da|daa|das|db|dd|de|dec|df|di|div|divpd|divps|divsd|divss|dl|dq|ds|dt|dw|emms|enter|f2xm1|fabs|fadd|faddp|fbld|fbstp|fchs|fclex|fcmovb|fcmovbe|fcmove|fcmovnb|fcmovnbe|fcmovne|fcmovnu|fcmovu|fcom|fcomi|fcomip|fcomp|fcompp|fcos|fdecstp|fdisi|fdiv|fdivp|fdivr|fdivrp|feni|ffree|fiadd|ficom|ficomp|fidiv|fidivr|fild|fimul|fincstp|finit|fist|fistp|fisub|fisubr|fld|fld1|fldcw|fldenv|fldl2e|fldl2t|fldlg2|fldln2|fldpi|fldz|fmul|fmulp|fnclex|fndisi|fneni|fninit|fnop|fnsave|fnstcw|fnstenv|fnstsw|fpatan|fprem|fprem1|fptan|frndint|frstor|fsave|fscale|fsetpm|fsin|fsincos|fsqrt|fst|fstcw|fstenv|fstp|fstsw|fsub|fsubp|fsubr|fsubrp|ftst|fucom|fucomi|fucomip|fucomp|fucompp|fwait|fxam|fxch|fxrstor|fxsave|fxtract|fyl2x|fyl2xp1|hlt|idiv|imul|in|inc|ins|insb|insd|insw|int|into|invd|invlpg|iret|iretd|ja|jae|jb|jbe|jc|jcxz|je|jecxz|jg|jge|jl|jle|jmp|jna|jnae|jnb|jnbe|jnc|jne|jng|jnge|jnl|jnle|jno|jnp|jns|jnz|jo|jp|jpe|jpo|js|jz|lahf|lar|ldmxcsr|lds|lea|leave|les|lfence|lfs|lgdt|lgs|lidt|lldt|lmsw|lock|lods|lodsb|lodsd|lodsw|loop|loope|loopne|loopnz|loopz|lsl|lss|ltr|maskmovdqu|maskmovq|maxpd|maxps|maxsd|maxss|mfence|minpd|minps|minsd|minss|mov|movapd|movaps|movd|movdq2q|movdqa|movdqu|movhlps|movhpd|movhps|movlhps|movlpd|movlps|movmskpd|movmskps|movntdq|movnti|movntpd|movntps|movntq|movq|movq2dq|movs|movsb|movsd|movss|movsw|movsx|movupd|movups|movzx|mul|mulpd|mulps|mulsd|mulss|neg|nop|not|or|orpd|orps|out|outs|outsb|outsd|outsw|packssdw|packsswb|packuswb|paddb|paddd|paddq|paddsb|paddsw|paddusb|paddusw|paddw|pand|pandn|pavgb|pavgw|pcmpeqb|pcmpeqd|pcmpeqw|pcmpgtb|pcmpgtd|pcmpgtw|pextrw|pinsrw|pmaddwd|pmaxsw|pmaxub|pminsw|pminub|pmovmskb|pmulhuw|pmulhw|pmullw|pmuludq|pop|popa|popad|popf|popfd|por|prefetchnta|prefetcht0|prefetcht1|prefetcht2|psadbw|pshufd|pshufhw|pshuflw|pshufw|pslld|pslldq|psllq|psllw|psrad|psraw|psrld|psrldq|psrlq|psrlw|psubb|psubd|psubq|psubsb|psubsw|psubusb|psubusw|psubw|punpckhbw|punpckhdq|punpckhqdq|punpckhwd|punpcklbw|punpckldq|punpcklqdq|punpcklwd|push|pusha|pushad|pushf|pushfd|pxor|rcl|rcpps|rcpss|rcr|rdmsr|rdpmc|rdtsc|rep|repe|repne|repnz|repz|ret|retf|rol|ror|rsm|rsqrtps|rsqrtss|sahf|sal|sar|sbb|scas|scasb|scasd|scasw|seta|setae|setb|setbe|setc|sete|setg|setge|setl|setle|setna|setnae|setnb|setnbe|setnc|setne|setng|setnge|setnl|setnle|setno|setnp|setns|setnz|seto|setp|setpe|setpo|sets|setz|sfence|sgdt|shl|shld|shr|shrd|shufpd|shufps|sidt|sldt|smsw|sqrtpd|sqrtps|sqrtsd|sqrtss|stc|std|sti|stmxcsr|stos|stosb|stosd|stosw|str|sub|subpd|subps|subsd|subss|sysenter|sysexit|test|ucomisd|ucomiss|ud2|unpckhpd|unpckhps|unpcklpd|unpcklps|verr|verw|wait|wbinvd|wrmsr|xadd|xchg|xlat|xlatb|xor|xorpd|xorps|pavgusb|pf2id|pfacc|pfadd|pfcmpeq|pfcmpge|pfcmpgt|pfmax|pfmin|pfmul|pfnacc|pfpnacc|pfrcp|pfrcpit1|pfrcpit2|pfrsqit1|pfrsqrt|pfsub|pfsubr|pi2fd|pmulhrw|pswapd|abstract|align|argc|argv|asm|assert|attribute|auto|bit|body|bool|break|byte|case|catch|cent|cfloat|char|class|complex|const|continue|creal|d_time|db|dd|de|debug|default|delete|deprecated|df|dg|di|do|double|ds|dynamic_cast|else|enum|envp|even|explicit|extended|extern|false|final|float|for|fp|friend|function|goto|idouble|if|ifloat|imaginary|in|inline|inout|instance|int|interface|ireal|long|mutable|naked|namespace|new|operator|out|override|private|protected|public|real|register|reinterpret_cast|return|short|signed|sizeof|static|struct|super|switch|synchronized|template|throw|true|try|typedef|typeid|typename|ubyte|ucent|uint|ulong|union|unsigned|ushort|using|version|virtual|void|volatile|wchar|while)\b");
            r.SetStyle(KeywordStyle2, @"\b(ClassInfo|E|Exception|FileException|LN10|LN2|LOG10E|LOG2|LOG2E|LOG2T|LocalTimetoUTC|M_1_PI|M_2_PI|M_2_SQRT|Object|OutBuffer|OutOfMemory|PI|PI_2|PI_4|RegExp|SQRT1_2|SQRT2|SliceStream|Stream|StringException|Thread|ThreadError|TicksPerSecond|UTCtoLocalTime|acos|addExt|addRange|addRoot|align2|align4|alignSize|altsep|append|asin|atan|atan2|atof|atoi|bsf|bsr|bt|btc|btr|bts|capitalize|capwords|ceil|center|close|cmp|copyFrom|copysign|cos|cosh|count|create|curdir|data|defaultExt|digits|enable|eof|exec|exp|expandtabs|expml|fabs|fill0|find|floor|fncharmatch|fnmatch|frexp|fullCollect|genCollect|getAll|getAttributes|getYnoteSettingsBaseName|getDirName|getDrive|getExt|getSize|getState|getThis|getUTCtime|getc|getcw|hdl|hexdigits|hypot|icmp|inp|inpl|inpw|insert|isabs|isalnum|isalpha|isascii|iscntrl|isdigit|isfinite|isgraph|isinf|islower|isnan|isnormal|isprint|ispunct|isspace|issubnormal|isupper|isxdigit|join|ldexp|letters|linesep|ljustify|log|log10|loglp|lowercase|maketrans|match|minimize|modf|octdigits|open|outp|outpl|outpw|pardir|parse|pathsep|pause|pauseAll|position|pow|printf|rand|rand_seed|read|readBlock|readExact|readLine|readString|readStringW|readable|remove|removeRange|removeRoot|rename|replace|replaceOld|replaceSlice|reserve|resume|resumeAll|rfind|rint|rjustify|rndtol|run|scanf|search|seek|seekCur|seekEnd|seekSet|seekable|sep|setPriority|signbit|sin|sinh|size|split|splitlines|spread|sqrt|start|strip|stripl|stripr|tan|tanh|test|thread_hdl|toByte|toBytes|toDateString|toHash|toInt|toLong|toShort|toString|toTimeString|toUbyte|toUint|toUlong|toUshort|tolower|toupper|translate|ungetc|ungetcw|uppercase|vprintf|vscanf|wait|whitespace|write|writeBlock|writeExact|writeLine|writeLineW|writeString|writeStringW|writeable|yield|zfill)\b");
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?\b", RegexCompiledOption);
            r.ClearFoldingMarkers();
            r.SetFoldingMarkers("{", "}");
        }
        private void PascalSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "{";
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, StringStyle, KeywordStyle, KeywordStyle2, NumberStyle, CharStyle);
            r.SetStyle(CommentStyle, new Regex(@"\(\*(.*?)\*\)", RegexOptions.Singleline|RegexCompiledOption));
            r.SetStyle(CommentStyle, @"({.*?})|({.*)", RegexOptions.Singleline);
            r.SetStyle(CommentStyle, @"({.*?})|(.*})", RegexOptions.Singleline | RegexOptions.RightToLeft);
            r.SetStyle(StringStyle, new Regex(@"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption));
            r.SetStyle(KeywordStyle, @"\b(and|array|as|asm|begin|case|class|const|constructor|destructor|dispinterfac|div|do|downto|else|end|except|exports|file|finalization|finally|for|function|goto|if|implementation|in|inherited|initialization|inline|interface|is|label|library|mod|nil|not|object|of|or|out|packed|procedure|program|property|raise|record|repeat|resourcestring|set|shl|shr|string|then|threadvar|to|try|type|unit|until|uses|var|while|with|xor)\b", RegexOptions.IgnoreCase);
            r.SetStyle(KeywordStyle2, @"\b(absolute|abstract|assembler|automated|cdecl|contains|default|dispid|dynamic|export|external|far|forward|implements|index|message|name|near|nodefault|overload|override|package|pascal|private|protected|public|published|read|readonly|register|reintroduce|requires|resident|safecall|stdcall|stored|virtual|write|writeonly)\b", RegexOptions.IgnoreCase);
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?\b");
            r.SetStyle(CharStyle, @"\:|\?|\*|%|=|\+|\!|\^|#|\,|\.|\\|@|\|");
            r.ClearFoldingMarkers();
            r.SetFoldingMarkers("{", "}");
            r.SetFoldingMarkers("Begin", "End", RegexOptions.IgnoreCase);
        }
        private void ASMSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = ";";
            r.tb.LeftBracket = '(';
            r.tb.LeftBracket2 = '[';
            r.tb.RightBracket = ')';
            r.tb.RightBracket2 = ']';
            r.ClearStyle(CommentStyle, StringStyle, KeywordStyle, KeywordStyle2, VariableStyle, NumberStyle, CharStyle);
            r.SetStyle(CommentStyle, @"\;.*$");
            r.SetStyle(StringStyle, new Regex( @"""""|''|"".*?[^\\]""|'.*?[^\\]'", RegexCompiledOption));
            r.SetStyle(KeywordStyle, @"\b(add|addb|addc|addcb|and|andb|bbc|bbs|bc|be|bge|bgt|bh|ble|blt|bmov|bmovi|bnc|bne|bnh|bnst|bnv|bnvt|br|bst|bv|bvt|call|clr|clrb|clrc|clrvt|cmp|cmpb|cmpl|dbnz|dbnzw|dec|decb|di|div|divb|divu|divub|djnz|djnzw|dpst|ei|eq|ext|extb|ge|gt|idlpd|inc|incb|jbc|jbs|jc|je|jge|jgt|jh|jle|jlt|jnc|jne|jnh|jnst|jnv|jnvt|jst|jv|jvt|lcall|ld|ldb|ldbse|ldbze|le|ljmp|lt|mod|mul|mulb|mulu|mulub|ne|neg|negb|nop|norml|not|notb|nul|or|orb|pop|popa|popf|push|pusha|pushf|ret|rst|scall|setc|shl|shlb|shll|shr|shra|shrab|shral|shrb|shrl|sjmp|skip|st|stb|sub|subb|subc|subcb|tijmp|trap|xch|xchb|xor|xorb)\b", RegexOptions.IgnoreCase);
            r.SetStyle(KeywordStyle2, @"\b(at|byte|cseg|dcb|dcl|dcp|dcr|dcw|dsb|dseg|dsl|dsp|dsr|dsw|dword|else|end|endif|endm|entry|equ|exitm|exitrn|far|if|irp|irpc|kseg|local|long|macro|main|module|null|org|oseg|pointer|public|rel|rept|rseg|set|stack|stacksize|word)\b", RegexOptions.IgnoreCase);
            r.SetStyle(VariableStyle, new Regex(@"\$[a-zA-Z_\d]*\b", RegexCompiledOption));
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?\b");
            r.SetStyle(CharStyle, @"\:|\?|\*|%|=|\+|\!|\^|#|\,|\.|\\|@|\|");
        }
        private void ScalaSyntaxHighlight(Range r)
        {
            r.tb.CommentPrefix = "//";
            CommentRegex1 = new Regex(@"//.*$", RegexOptions.Multiline);
            CommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline);
            CommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft);
            r.ClearStyle(CommentStyle, KeywordStyle, KeywordStyle2);
            r.SetStyle(CommentStyle, CommentRegex1);
            r.SetStyle(CommentStyle, CommentRegex2);
            r.SetStyle(CommentStyle, CommentRegex3);
            r.SetStyle(KeywordStyle3, new Regex(@"#[define|elif|else|endif|error|if|undef|warning]*\b"));
            r.SetStyle(KeywordStyle, @"\b(abstract|boolean|break|byte|case|catch|char|class|continue|default|delegate|do|double|else|extends|false|final|finally|float|for|if|implements|import|instanceof|int|interface|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|void|volatile|while)\b");
            r.SetStyle(KeywordStyle2, @"\b(def|object|val|var|trait|type|override|with|sealed|yield|match|implicit|requires)\b");
            r.SetStyle(NumberStyle, @"\b\d+[\.]?\d*([eE]\-?\d+)?\b");
            r.SetStyle(CharStyle, @"=|>|<|\[|\]|\(|\)|\?|\$|\!|\*|\^");
        }

         #region OpenCL

         private const string TypePattern = @"void|bool|char|uchar|short|ushort|int|uint|long|ulong|float|double|half|size_t|char2|uchar2|short2|ushort2|int2|uint2|long2|ulong2|float2|double2|char4|uchar4|short4|ushort4|int4|uint4|long4|ulong4|float4|double4|char8|uchar8|short8|ushort8|int8|uint8|long8|ulong8|float8|double8|char16|uchar16|short16|ushort16|int16|uint16|long16|ulong16|float16|double16";
         private const string FlowPattern = @"for|while|if|else|return";
         private const string ExtensionsPattern = @"cl_khr_fp64|cl_khr_global_int32_YnoteSettingsBase_atomics|cl_khr_global_int32_extended_atomics|cl_khr_local_int32_YnoteSettingsBase_atomics|cl_khr_local_int32_extended_atomics|cl_khr_int64_YnoteSettingsBase_atomics|cl_khr_int64_extended_atomics|cl_khr_3d_image_writes|cl_khr_byte_addressable_store|cl_khr_fp16";
         private const string QualifiersPattern = @"kernel|read_only|write_only|global|local|constant|private|__kernel|__read_only|__write_only|__global|__local|__constant|__private|__attribute__|reqd_work_group_size|work_group_size_hint|vec_type_hint|const";
         private const string WorkItemFuncPattern = @"get_work_dim|get_global_size|get_global_id|get_local_size|get_local_id|get_num_groups|get_group_id";
         private const string ConstantsPattern = @"MAXFLOAT|HUGE_VALF|INFINITY|NAN|M_E|M_LOG2E|M_LOG10E|M_LN2|M_LN10|M_PI|M_PI_2|M_PI_4|M_1_PI|M_2_PI|M_2_SQRTPI|M_SQRT2|M_SQRT1_2";
         private const string MathFuncPattern = @"acos|acosh|acospi|asin|asinh|asinpi|atan|atan2|atanh|atanpi|atan2pi|cbrt|ceil|copysign|cos|cosh|cospi|erfc|erf|axp|axp2|axp10|expm1|fabs|fdim|floor|fma|fmax|fmin|fmod|fract|frexp|hypot|ilogb|ldexp|lgamma|lgamma_r|log|log2|log10|log1p|logb|mad|modf|nan|nextafter|pow|pown|powr|remainder|remquo|rint|rootn|round|rsqrt|sin|sincos|sinh|sinpi|sqrt|tan|tanh|tanpi|tgamma|trunc";
         private const string NativeMathFuncPattern = @"native_cos|native_divide|native_exp|native_exp2|native_exp10|native_log|native_log2|native_log10|native_powr|native_recip|native_rsqrt|native_sin|native_sqrt|native_tan";
         private const string CommonFuncPattern = @"clamp|degress|max|min|mix|radians|step|smoothstep|sign";
         private const string GeomFuncPattern = @"cross|dot|distance|length|normalize";
         private const string FastGeomFuncPattern = @"fast_distance|fast_length|fast_normalize";
         private const string ImageFuncPattern = @"sampler_t|image2d_t|read_imagef|read_imagei|read_imageui|write_imagef|write_imagei|write_imageui|CLK_FILTER_NEAREST|CLK_FILTER_LINEAR|CLK_NORMALIZED_COORDS_FALSE|CLK_NORMALIZED_COORDS_TRUE|CLK_ADDRESS_CLAMP_TO_EDGE|CLK_ADDRESS_CLAMP|CLK_ADDRESS_NONE";
         private const string SynchFuncPattern = @"barrier|mem_fence|CLK_LOCAL_MEM_FENCE|CLK_GLOBAL_MEM_FENCE|read_mem_fence|write_mem_fence";
         private const string OtherPattern = @"#pragma|#define";

        static Regex TypeRegex, CommentRegex1, CommentRegex2, CommentRegex3, NumberRegex, FuncNameRegex, FlowRegex, WorkItemFuncRegex, ConstantsRegex, ExtensionsRegex, QualifiersRegex, FuncRegex, ImageRegex, SynchFuncRegex, OtherRegex, FuncSignatureRegex, FuncSignatureParserRegex;

        static void InitCLRegex()
        {
            TypeRegex = new Regex(string.Format(@"\b({0})\b", TypePattern), RegexCompiledOption);
            CommentRegex1 = new Regex(@"//.*$", RegexOptions.Multiline | RegexCompiledOption);
            CommentRegex2 = new Regex(@"(/\*.*?\*/)|(/\*.*)", RegexOptions.Singleline | RegexCompiledOption);
            CommentRegex3 = new Regex(@"(/\*.*?\*/)|(.*\*/)", RegexOptions.Singleline | RegexOptions.RightToLeft | RegexCompiledOption);
            NumberRegex = new Regex(@"\b\d+[\.]?\d*([e]\-?\d+)?[hulf]?\b|\b0x[a-f\d]+\b", RegexCompiledOption | RegexOptions.IgnoreCase);
            FuncNameRegex = new Regex(string.Format(@"\b({0})\s+(?<range>[\w\d_]+)\s*\(", TypePattern), RegexCompiledOption);
            FuncSignatureRegex = new Regex(string.Format(@"\b({0})\s+[\w\d_]+\s*\([^\)]*?\)", TypePattern), RegexCompiledOption);
            FuncSignatureParserRegex = new Regex(string.Format(@"^(?<type>\S+)\s+(?<name>[\w\d_]+)\s*\((?<args>[^\)]*?)\)$"), RegexCompiledOption);
            FlowRegex = new Regex(string.Format(@"\b({0})\b", FlowPattern), RegexCompiledOption);
            WorkItemFuncRegex = new Regex(string.Format(@"\b({0})\b", WorkItemFuncPattern), RegexCompiledOption);
            ConstantsRegex = new Regex(string.Format(@"\b({0})\b", ConstantsPattern), RegexCompiledOption);
            ExtensionsRegex = new Regex(string.Format(@"\b({0})\b", ExtensionsPattern), RegexCompiledOption);
            QualifiersRegex = new Regex(string.Format(@"\b({0})\b", QualifiersPattern), RegexCompiledOption);
            FuncRegex = new Regex(string.Format(@"\b({0}|{1}|{2}|{3}|{4})\b", MathFuncPattern, NativeMathFuncPattern, CommonFuncPattern, GeomFuncPattern, FastGeomFuncPattern), RegexCompiledOption);
            ImageRegex = new Regex(string.Format(@"\b({0})\b", ImageFuncPattern), RegexCompiledOption);
            SynchFuncRegex = new Regex(string.Format(@"\b({0})\b", SynchFuncPattern), RegexCompiledOption);
            OtherRegex = new Regex(string.Format(@"({0})\b", OtherPattern), RegexCompiledOption);
        }

        static public List<string> GetAllKeywords()
        {
            List<string> result = new List<string>();
            result.AddRange(TypePattern.Split('|'));
            result.AddRange(FlowPattern.Split('|'));
            result.AddRange(ExtensionsPattern.Split('|'));
            result.AddRange(QualifiersPattern.Split('|'));
            result.AddRange(WorkItemFuncPattern.Split('|'));
            result.AddRange(ConstantsPattern.Split('|'));
            result.AddRange(MathFuncPattern.Split('|'));
            result.AddRange(NativeMathFuncPattern.Split('|'));
            result.AddRange(CommonFuncPattern.Split('|'));
            result.AddRange(GeomFuncPattern.Split('|'));
            result.AddRange(FastGeomFuncPattern.Split('|'));
            result.AddRange(ImageFuncPattern.Split('|'));
            result.AddRange(SynchFuncPattern.Split('|'));
            result.AddRange(OtherPattern.Split('|'));

            return result;
        }

        private void CLHighlight(Range range, List<ExplorerItem> customFunctions)
        {
            range.tb.CommentPrefix = "//";
            //build regex for custom functions
            StringBuilder sb = new StringBuilder();
            foreach (var func in customFunctions)
                sb.Append(func.funcName + "|");
            Regex CustomFuncRegex = new Regex(@"\b("+sb.ToString().TrimEnd('|')+@")\b");
            //
            range.tb.LeftBracket = '(';
            range.tb.RightBracket = ')';
            range.tb.LeftBracket2 = '[';
            range.tb.RightBracket2 = ']';
            //clear
            range.ClearStyle(CommentStyle, NumberStyle, FunctionsStyle, KeywordStyle2, KeywordStyle3, HtmlEntityStyle, TypesStyle, ClassNameStyle);
            //comment
            range.SetStyle(CommentStyle, CommentRegex1);
            range.SetStyle(CommentStyle, CommentRegex2);
            range.SetStyle(CommentStyle, CommentRegex3);
            //number
            range.SetStyle(NumberStyle, NumberRegex);
            //func name
            range.SetStyle(FunctionsStyle, FuncNameRegex);
            //keywords
            range.SetStyle(KeywordStyle2, ExtensionsRegex);
            range.SetStyle(KeywordStyle3, QualifiersRegex);
            range.SetStyle(KeywordStyle, TypeRegex);
            range.SetStyle(KeywordStyle, FlowRegex);
            range.SetStyle(KeywordStyle2, WorkItemFuncRegex);
            range.SetStyle(HtmlEntityStyle, ConstantsRegex);
            range.SetStyle(TypesStyle, FuncRegex);
            range.SetStyle(KeywordStyle3, OtherRegex);
            range.SetStyle(VariableStyle, ImageRegex);
            range.SetStyle(TypesStyle, SynchFuncRegex);
            range.SetStyle(ClassNameStyle, CustomFuncRegex);

            //clear folding markers
            range.ClearFoldingMarkers();
            //set folding markers
            range.SetFoldingMarkers("{", "}");//allow to collapse brackets block
            range.SetFoldingMarkers(@"/\*", @"\*/");//allow to collapse comment block
        }

        static List<ExplorerItem> BuildExplorerItems(Range range)
        {
            if (TypeRegex == null)
                InitCLRegex();
            List<ExplorerItem> list = new List<ExplorerItem>();

            foreach (var r in range.GetRanges(FuncSignatureRegex))
            {
                var m = FuncSignatureParserRegex.Match(r.Text);
                if (!m.Success)
                    continue;
                var item = new ExplorerItem() { type = ExplorerItemType.Method, line = r.Start.iLine, funcName = m.Groups["name"].Value, funcType = CLType.Parse(m.Groups["type"].Value) };
                item.args = ParseFuncArgs(m.Groups["args"].Value);
                list.Add(item);
            }

            list.Sort(new ExplorerItemComparer());

            return list;
        }

        static List<FunctionArgument> ParseFuncArgs(string text)
        {
            List<FunctionArgument> res = new List<FunctionArgument>();
            var parts = text.Trim().Split(',');
            foreach (var part in parts)
            {
                var parts2 = part.Split(new char[] { ' ', '*' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts2.Length < 2)
                    continue;
                bool isPointer = part.Contains("*");
                var arg = new FunctionArgument() { name = parts2[parts2.Length - 1], type = CLType.Parse(parts2[parts2.Length - 2] + (isPointer ? "*" : "")) };
                res.Add(arg);
            }

            return res;
        }
        #endregion
        #endregion

    }
}
